package com.uphone.kingmall.activity.personal.set;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.core.content.FileProvider;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.china.zhuoyue.BuildConfig;
import com.china.zhuoyue.R;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.uphone.kingmall.base.BaseActivity;
import com.uphone.kingmall.listener.onUploadFileListener;
import com.uphone.kingmall.utils.CaptureFileUtils;
import com.uphone.kingmall.utils.CommonUtil;
import com.uphone.kingmall.utils.GlideCircleTransform;
import com.uphone.kingmall.utils.MyUrl;
import com.uphone.kingmall.utils.OkGoUtils;
import com.uphone.kingmall.utils.PermissionsUtils;
import com.uphone.kingmall.utils.SharedPreferencesHelper;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import butterknife.BindView;
import butterknife.OnClick;

public class MineHeadResetActivity extends BaseActivity {


    private static final int PHOTO_REQUEST_CAMERA = 1;
    private static final int PHOTO_REQUEST_GALLERY = 2;
    private static final String PHOTO_FILE_NAME = "temp_photo.jpg";
    private static final String PHOTO_FILE_NAME1 = "temp_photo1.jpg";
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    @BindView(R.id.btn_save)
    TextView btnSave;
    @BindView(R.id.ll)
    FrameLayout ll;
    private File tempFile;
    private File cropPhoto;
    private static final int PHOTO_REQUEST_CUT = 3;

    @Override
    public int getLayoutContentId() {
        return R.layout.kingmall_activity_mine_head_reset;
    }

    @Override
    public void initView() {
        CommonUtil.initTitle(this, "更换用户头像", ll);

    }

    @Override
    public void initData() {
        if (!TextUtils.isEmpty(SharedPreferencesHelper.getUserImg())) {
            Glide.with(getApplication()).load(SharedPreferencesHelper.getUserImg()).apply(new RequestOptions().optionalTransform(new GlideCircleTransform())).into(ivHead);
        }
    }

    @OnClick({R.id.btn_submit, R.id.btn_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_submit:
                showDialog();
                break;
            case R.id.btn_save:
                saveImg();
                break;
        }
    }

    private void saveImg() {
        if (cropPhoto == null) {
            ToastUtils.showShort("您还没有选择图片");
        } else {

            OkGoUtils.upLoadFile(MyUrl.editPhoto, this, null, "img", cropPhoto, new onUploadFileListener() {
                @Override
                public void onStart() {
                    LogUtils.e("开始上传");
                }

                @Override
                public void onUploadProgress(Progress progress) {

                }

                @Override
                public void onSuccess(String body, int code) {
                    if (code == 0) {
                        ToastUtils.showShort("上传成功");
                        if (cropPhoto != null && cropPhoto.exists()) {
                            cropPhoto.delete();
                        }
                    }
                }

                @Override
                public void onError(Response<String> response) {
                    ToastUtils.showShort("上传失败，请重试");

                }

                @Override
                public void onFinish() {

                }
            });
        }
    }

    private void showDialog() {
        final CharSequence[] items = {"相册", "拍照"};
        AlertDialog dlg = new AlertDialog.Builder(this)
                .setTitle("选择图片")
                .setItems(items, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, final int item) {
                        // 这里item是根据选择的方式，
                        PermissionsUtils.getInstance().checkPermissions(MineHeadResetActivity.this, new PermissionsUtils.IPermissionsResult() {
                            @Override
                            public void passPermissions() {
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    if (item == 0) {
                                        Intent intent = new Intent(Intent.ACTION_PICK);
                                        intent.setType("image/*");
                                        startActivityForResult(intent,
                                                PHOTO_REQUEST_GALLERY);
                                    } else {
                                        StartTakePhoto();

                                    }
                                } else {
                                    if (item == 0) {
                                        Intent intent = new Intent(Intent.ACTION_PICK);
                                        intent.setType("image/*");
                                        startActivityForResult(intent,
                                                PHOTO_REQUEST_GALLERY);
                                    } else {
                                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                                            tempFile = new File(Environment
                                                    .getExternalStorageDirectory(),
                                                    PHOTO_FILE_NAME);
                                            Uri uri = Uri.fromFile(tempFile);
                                            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                                            startActivityForResult(intent,
                                                    PHOTO_REQUEST_CAMERA);
                                        } else {
                                            ToastUtils.showShort("未找到存储卡，无法存储照片！");
                                        }
                                    }

                                }
                            }

                            @Override
                            public void refusePermissions() {

                            }
                        }, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                    }
                }).create();
        dlg.show();
    }

    void StartTakePhoto() {
        tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
        CaptureFileUtils.startActionCapture(this, tempFile, PHOTO_REQUEST_CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHOTO_REQUEST_GALLERY) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri != null) {
                    crop(uri, 1);
                }
            } else {
                Log.e("radish", "图片NOT ");
            }

        } else if (requestCode == PHOTO_REQUEST_CAMERA) {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                if (tempFile != null && tempFile.exists()) {
                    LogUtils.e("tempFile.getPath()：" + tempFile.getPath());
                    crop(Uri.fromFile(tempFile), 0);
                }
            } else {
                Toast.makeText(this, "未找到存储卡，无法存储照片！", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == PHOTO_REQUEST_CUT) {
            try {
                final byte[] bytes = InputStream2ByteArray(cropPhoto.getAbsolutePath());
                if (bytes != null && bytes.length > 0) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Glide.with(getApplication()).load(bytes).apply(new RequestOptions().optionalTransform(new GlideCircleTransform())).into(ivHead);

                            try {
                                if (tempFile != null && tempFile.exists()) {
                                    tempFile.delete();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, 200);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private byte[] InputStream2ByteArray(String filePath) throws IOException {
        InputStream in = new FileInputStream(filePath);
        byte[] data = toByteArray(in);
        in.close();

        return data;
    }

    private byte[] toByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }


    private void crop(Uri uri, int type) {
        Uri outputUri;

        Intent intent = new Intent("com.android.camera.action.CROP");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
        }

        if (type == 0) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".myFileProvider", tempFile);
            } else {
                uri = Uri.fromFile(tempFile);
            }
        }

        cropPhoto = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME1);
        if (cropPhoto.exists()) {
            cropPhoto.delete();
        }
        try {
            cropPhoto.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        outputUri = Uri.fromFile(cropPhoto);


        intent.setDataAndType(uri, "image/*");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
        }
        // 下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);

        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);

        //输出的宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 300);

        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection
        startActivityForResult(intent, PHOTO_REQUEST_CUT);
    }
}
